package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.*;
import com.itheima.entity.PageCondition;
import com.itheima.entity.PageResult;


import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.mapper.Order_Address_Mapper;
import com.itheima.service.OrderService;
import com.itheima.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

//体检预约
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private Order_Address_Mapper order_address_mapper;

    //体检预约
    public Result order(Map map) throws Exception {
        //检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        //查询预约设置
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(DateUtils.parseString2Date(orderDate));
        //预约设置为空
        if (orderSetting == null) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户手机号
        Member member = memberMapper.findByTelephone(telephone);//获取会员
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员Id
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐Id
            Order order = new Order(memberId, order_Date, Integer.valueOf(setmealId));
            //根据条件进行查询
            List<Order> list = orderMapper.findByCondition(order);
            if (list != null && list.size() > 0) {
                //说明用户在重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null) {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberMapper.add(member);//自动完成会员注册
        }
        //预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderMapper.add(order);
        orderSetting.setReservations(orderSetting.getReservations() + 1);//已预约人数+1
        orderSettingMapper.editReservationsByOrderDate(orderSetting);


        // 需要向 t_order_address 中间表中添加数据
        int orderId = order.getId();
        int addressId = (Integer) map.get("address");
        order_address_mapper.insert(orderId , addressId);


        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    public Map findById(Integer id) throws Exception {
        return orderMapper.findById4Detail(id);
    }

    //通过会员id查询套餐信息
    public List<Setmeal> findSetmealById(Integer id) {
        List<Setmeal> list = orderMapper.findSetmealById(id);
        return list;
    }

    //通过会员id和日期查询套餐信息
    public List<Setmeal> findSetmealByIdAndDate(String memberId, String startDate, String endDate) {
        return orderMapper.findSetmealByIdAndDate(memberId, startDate, endDate);
    }

    /*---------------------------------------------*/

    /*查询所有的套餐*/
    @Override
    public List<Setmeal> findSetmeal() {
        return orderMapper.findSetmeal();
    }

    /*新增预约*/
    @Override
    public Result result(Integer setmealIds, Map map) throws Exception {
        /*判断用户预约时间*/
        String orderTime = (String) map.get("orderDate");
        Date orderDate = method3(DateUtils.parseString2Date(orderTime));
        if (!method(setmealIds, map)) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        /*判断当天是否已经进行的预约设置*/
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDate);
        if (orderSetting == null) {
            /*当日没有进行预约设置*/
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        /*判断用户所选择分日期是否已经约满*/
        if (!method1(orderSetting)) {
            /*预约已满*/
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        Member m = new Member();
        /*获取用户的手机号码，判断用户是否为会员*/
        String phoneNumber = (String) map.get("phoneNumber");
        Member member = memberMapper.findByTelephone(phoneNumber);
        if (member != null) {
            /*判断用户是否重复预约*/
            Integer memberId = member.getId();/*会员id*/
            /*将条件封装到Order对象进行传递*/
            Order order = new Order(memberId, orderDate, setmealIds);
            List<Order> list = orderMapper.findByCondition(order);
            if (list != null && list.size() > 0) {
                /*用户重复预约，无法预约*/
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            /*该用户不是会员，自动注册*/
            m.setRegTime(new Date());
            m.setPhoneNumber(phoneNumber);/*手机号码*/
            m.setName((String) map.get("order_name"));/*会员姓名*/
            m.setBirthday(new Date());
            /*注册会员*/
            memberMapper.saveMember(m);
        }

        /*完成预约*/
        Order order = new Order();
        order.setMemberId(m.getId());//设置会员ID
        order.setOrderDate(orderDate);//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(setmealIds);//套餐ID
        orderMapper.add(order);
        /*已预约人数加一*/
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingMapper.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /*分页查询*/
    @Override
    public PageResult findPage(String param, Map map) throws Exception {
        if (map.size() == 0) {
            /*不进行条件查询*/
            String[] split = param.split(",");
            Integer currentPage = Integer.parseInt(split[0]);/*获取当前页码*/
            Integer pageSize = Integer.parseInt(split[1]);/*每页记录数*/
            PageHelper.startPage(currentPage, pageSize);
            Page<Order> page = orderMapper.findAll();
            long total = page.getTotal();
            List<Order> rows = page.getResult();
            return new PageResult(total, rows);
        }

        /*进行条件查询*/
        List<String> orderDate = (List<String>) map.get("orderDate");
        PageCondition pageCondition = new PageCondition();
        if (orderDate != null && orderDate.size() > 0) {
            Date date1 = DateUtils.parseString2Date(orderDate.get(0));
            Date date2 = DateUtils.parseString2Date(orderDate.get(1));
            pageCondition.setStartDate(DateUtils.parseDate2String(date1));
            pageCondition.setEndDate(DateUtils.parseDate2String(date2));
        }
        pageCondition.setOrderType((String) map.get("orderType"));
        pageCondition.setOrderStatus((String) map.get("orderStatus"));
        pageCondition.setNameOrPhone((String) map.get("nameOrPhone"));
        String[] split = param.split(",");
        Integer currentPage = Integer.parseInt(split[0]);/*获取当前页码*/
        Integer pageSize = Integer.parseInt(split[1]);/*每页记录数*/
        PageHelper.startPage(currentPage, pageSize);
        Page<Order> page = orderMapper.findAllByCondition(pageCondition);
        //long total = page.getTotal();
        List<Order> rows = page.getResult();
        long total = rows.size();
        return new PageResult(total, rows);
    }


    /*删除预约数据*/
    @Override
    public void delete(Integer id) throws Exception {
        /*获取当前预约状态*/
        Order order = orderMapper.findStatusById(id);
        //获取用户预约的日期
        Date orderDate = order.getOrderDate();
        //如果是未到诊的话，当天预约人数加一
        OrderSetting orderSetting = new OrderSetting();
        orderSetting.setOrderDate(orderDate);
        if (order.getOrderStatus().equals("未到诊")) {
            orderSettingMapper.setOrderNumber(orderSetting);
        }

        /*删除预约记录*/
        orderMapper.delete(id);
    }

    /*更新预约状态*/
    @Override
    public void updateStatus(Integer id) {
        /*查询当前预约状态*/
        Order order = orderMapper.findStatusById(id);
        if (order.getOrderStatus().equals("未到诊")) {
            orderMapper.updateStatus(id);
        } else {
            orderMapper.updateStatusTo(id);
        }
    }

    /*根据id查询预约数据*/
    @Override
    public Map findOrderById(Integer id) {
        return orderMapper.findOrderById(id);
    }

    /*查询套餐id*/
    @Override
    public List<Integer> findSetmealId(Integer id) {
        return orderMapper.findSetmealId(id);
    }


    /*更新预约数据*/
    @Override
    public Result resultByUpdate(Integer setmealIds, Map map) throws Exception {
        /*转换日期格式*/
        String orderTime = (String) map.get("orderDate");
        Date orderDate = DateUtils.parseString2Date(orderTime);
        Order orderOne = orderMapper.findStatusById((Integer) map.get("id"));
        long time = orderOne.getOrderDate().getTime();
        long dateTime = orderDate.getTime();
        if (dateTime != time) {
            orderDate = method3(DateUtils.parseString2Date(orderTime));
        }

        /*判断用户预约时间*/
        if (!method(setmealIds, map)) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        /*判断当天是否已经进行的预约设置*/
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDate);
        if (orderSetting == null) {
            /*当日没有进行预约设置*/
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        /*判断用户所选择分日期是否已经约满*/
        if (!method1(orderSetting)) {
            /*预约已满*/
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        /*拿到该用户的会员id*/
        Integer m_id = (Integer) map.get("m_id");
        String m_name = (String) map.get("m_name");
        /*更新会员信息*/
        memberMapper.updateByOrder(m_name, m_id);

        /*获取当前预约状态*/
        Order orderTp = orderMapper.findStatusById((Integer) map.get("id"));
        //如果是未到诊的话，当天预约人数加一
        orderSetting = new OrderSetting();
        orderSetting.setOrderDate(orderTp.getOrderDate());
        if (orderTp.getOrderStatus().equals("未到诊")) {
            /*更新之前的已预约人数减一*/
            orderSettingMapper.setOrderNumber(orderSetting);
        }

        /*获取修改后的表单数据*/
        Order order = new Order();
        order.setOrderDate(orderDate);/*预约时间*/
        order.setOrderType((String) map.get("orderType"));/*预约类型*/
        order.setOrderStatus((String) map.get("orderStatus"));/*预约状态*/
        order.setSetmealId(setmealIds);/*套餐名称*/
        order.setId((Integer) map.get("id"));
        /*更新预约数据*/
        orderMapper.resultByUpdate(order);

        /*获取当前预约状态*/
        orderTp = orderMapper.findStatusById((Integer) map.get("id"));
        //如果是未到诊的话，当天预约人数加一
        orderSetting = new OrderSetting();
        orderSetting.setOrderDate(orderDate);
        if (orderTp.getOrderStatus().equals("未到诊")) {
            /*更新之后的已预约人数加一*/
            orderSettingMapper.setOrderNumberTo(orderSetting);
        }

        return new Result(true, "更新成功!");
    }

    /*判断客户预约时间*/
    public boolean method(Integer setmealIds, Map map) throws Exception {
        /*转换日期格式*/
        String orderTime = (String) map.get("orderDate");
        Date orderDate = method3(DateUtils.parseString2Date(orderTime));
        /*判断用户预约日期是否合法*/
        long time = orderDate.getTime();
        Date date = new Date();
        long time1 = date.getTime();
        if (time1 - time > 0) {
            return false;
        }
        return true;
    }

    /*判断用户所选择分日期是否已经约满*/
    public boolean method1(OrderSetting orderSetting) throws Exception {
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (number <= reservations) {
            /*当天预约人数已满，无法预约*/
            return false;
        }
        return true;
    }

    /*格式日期*/
    public Date method3(Date date) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        String s = DateUtils.parseDate2String(calendar.getTime());
        Date date1 = DateUtils.parseString2Date(s);
        return date1;
    }

    public Date method4(Date date) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        String s = DateUtils.parseDate2String(calendar.getTime());
        Date date1 = DateUtils.parseString2Date(s);
        return date1;
    }


    //更新就诊状态
    public void statusEdit(Order order) {
        orderMapper.statusEdit(order);
    }

    //健康干预查询所有预约信息
    public PageResult findPage22(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<OrderList> page = orderMapper.selectByCondition(queryString);

        Long total = page.getTotal();
        List rows = page.getResult();

        return new PageResult(total,rows);
    }
}
